<script setup lang="ts">
import '../../assets/icon/iconfont.js'
import { onMounted, ref, watch } from 'vue';
import { useArticle } from '@/hooks/articleHook';
import type { articleData } from '@/utils/interface';
import ArticleCar2 from './car/articleCar2.vue';

const {
  getArticle,
  articleList,
  articlCount, // 总文章数量
} = useArticle(); //管理标签选择

const props = defineProps({
  pageSize: {
    type: Number,
    default: 4,
  },
  subsetId: {
    type: [Number, String],
    default: -1,//-1表示全部

  },
  searchTerm: {
    type: String,
    default: '',
  },
})

// 分页状态
const currentPage = ref(1);
const isLoading = ref(false);
const hasMore = ref(true);

const request = {
  pageSize: props.pageSize,
  nowPage: currentPage.value,
  state:1,//1表示已发布，0表示未发布
  subset_id: props.subsetId,
  searchTerm: props.searchTerm,
  classify: 0,//0表示文章，1表示图库
  count: true,
}

//文章列表
const articles = ref<articleData[]>([]);
// 监听articleList变化，更新articles
watch(articleList, (newVal) => {
  articles.value.push(...newVal);
  // 检查是否加载完所有文章
    if(articles.value.length===articlCount.value) {
    hasMore.value = false;
  };
  console.log('articles', articles.value);

})


// 加载更多文章
const loadMore = async () => {
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  currentPage.value++;
  request.nowPage = currentPage.value;
  try {
    getArticle(request);
  } catch (error) {
    console.error('加载失败:', error);
    currentPage.value--; // 回滚页码
  } finally {
    isLoading.value = false;
  }
}

// 防抖函数
let timer: ReturnType<typeof setTimeout> | null = null;
const debounceLoadMore = () => {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    loadMore();
  }, 300);
}

watch(() => [props.subsetId, props.searchTerm], () => {
  request.subset_id = props.subsetId;
  request.searchTerm = props.searchTerm;
  articles.value = [];
  currentPage.value = 1;
  hasMore.value = true;
  console.log('props.subsetId', request);
  getArticle(request);
})


onMounted(() => {
  getArticle(request);
})


</script>

<template>
  <!-- 文章列表内容 -->
    <!-- 文章卡片一 -->
    <ArticleCar2 :articleList="articles" :searchTerm="props.searchTerm" />

  <!-- 加载更多按钮 -->
  <div class="w-full flex justify-center items-center mb-10">
    <button :disabled="isLoading || !hasMore" :class="[
      'border-2 text-xl px-4 py-2 rounded-full cursor-pointer transition-all duration-300',
      isLoading || !hasMore
        ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
        : 'hover:bg-amber-500 hover:scale-105'
    ]" @click="debounceLoadMore"> {{ isLoading ? '加载中...' : hasMore ? '加载更多' : '没有更多了' }}</button>
  </div>
</template>

<style scoped>
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.icon--large {
  width: 2em;
  height: 2em;
}
</style>
